#coding=utf-8
from django.shortcuts import render,redirect
from django.views.decorators.csrf import csrf_exempt
from WebApp.models import Users
from django.http import HttpResponse, HttpResponseRedirect
import json
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
# Create your views here.

@login_required()
@csrf_exempt
def index(request):
    return render(request, 'WebApp/index.html')

@csrf_exempt
def user_login(request):
    if request.session.get('login_status', None):
        return redirect('/noun/index')
    if request.method == "POST":
        username = request.POST.get('username')
        password = request.POST.get('password')
        if username and password:
            user = authenticate(username=username, password=password)
            if user:
                if user.is_active:
                    login(request, user)
                    request.session['login_status'] = True
                    request.session['user_name'] = user.username
                    message = {
                        "login_status": "True",
                    }
                    return HttpResponse(json.dumps(message))
                else:
                    message = {"msginfo": u'用户未激活'}
                    return HttpResponse(json.dumps(message))
            else:
                message = {"msginfo": u'用户名或密码错误'}
                return HttpResponse(json.dumps(message))
        else:
            message = {"msginfo": u'请输入用户名或密码'}
            return HttpResponse(json.dumps(message))

    return render(request, 'WebApp/login.html')


@csrf_exempt
def user_logout(request):
    if not request.session.get('login_status', None):
        return redirect('/noun/index')
    logout(request)
    request.session.flush()
    return redirect('/noun/login')

def set_response_data(code=0, data=None, error=None):
    return json.dumps({
        'code': code,
        'error_info': error,
        'data': data
    })

@login_required()
@csrf_exempt
def users_manage(request):
    user_name = request.session.get('user_name')
    ret = {
        'Usersdata': [],
        'count': 0,
        'user_name': user_name,
    }
    if request.method == "GET":
        refresh = request.GET.get("refresh",None)
        if refresh:
            try:
                start = int(request.GET['offset'])
                end = start + int(request.GET['pageSize'])
                users = Users.objects.all()
                result = []
                for user in users:
                    info = {
                        "id": user.id,
                        "username": user.username,
                        "name": user.name,
                        "email": user.email,
                        "phone": user.phone,
                        "is_admin": user.is_admin,
                        "is_active": user.is_active,
                    }
                    result.append(info)
                count = len(result)
                rows = result[start:end]
            except:
                rows = []
                count = 0,
            finally:
                return HttpResponse(set_response_data(data={'count': count, 'rows': rows}))
        else:
            return render(request, 'WebApp/user_manage.html', ret)
    #post请求
    else:
        ###判断post参数
        if request.POST.get('type'):
            type = request.POST.get('type')
            if type == "del":
                username = request.POST.get('username')
                ###删除用户
                try:
                    Users.objects.filter(username=username).delete()
                    return HttpResponse(json.dumps({"msginfo": u'用户删除成功'}))
                except:
                    return HttpResponse(json.dumps({"msgerror": u'用户删除失败'}))
            else:
                ###添加用户
                pass

        else:
            ###修改用户信息
            username = request.POST.get('username')
            is_admin = request.POST.get('is_admin')
            is_active = request.POST.get('is_active')
            try:
                users = Users.objects.get(username=username)
                users.is_admin = is_admin
                users.is_active = is_active
                users.save()
                return HttpResponse(json.dumps({"msginfo": u'用户信息修改成功'}))
            except:
                return HttpResponse(json.dumps({"msgerror": u'用户信息修改失败'}))
